package com.easy.dn.utils.encryption;


import com.easy.dn.utils.exception.ErrorCode;
import com.easy.dn.utils.exception.ErrorException;

import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

public final class RSA {
    private RSA() {
    }
    /**
     * 指定key的大小
     */
    private static int keySize = 1024;

    /**
     * 生成密钥对
     */
    public static Map<String, String> generateKeyPair() throws Exception {
        /** RSA算法要求有一个可信任的随机数源 */
        SecureRandom sr = new SecureRandom();
        /** 为RSA算法创建一个KeyPairGenerator对象 */
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(Constants.Algorithm.RSA.algorithm());
        /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
        kpg.initialize(keySize, sr);
        /** 生成密匙对 */
        KeyPair kp = kpg.generateKeyPair();
        /** 得到公钥 */
        Key publicKey = kp.getPublic();
        byte[] publicKeyBytes = publicKey.getEncoded();
        String pub = new String(Base64.encodeBase64(publicKeyBytes), Constants.CHAR_ENCODING);
        /** 得到私钥 */
        Key privateKey = kp.getPrivate();
        byte[] privateKeyBytes = privateKey.getEncoded();
        String pri = new String(Base64.encodeBase64(privateKeyBytes), Constants.CHAR_ENCODING);

        Map<String, String> map = new HashMap<String, String>();
        map.put("publicKey", pub);
        map.put("privateKey", pri);
        RSAPublicKey rsp = (RSAPublicKey) kp.getPublic();
        BigInteger bint = rsp.getModulus();
        byte[] b = bint.toByteArray();
        byte[] deBase64Value = Base64.encodeBase64(b);
        String retValue = new String(deBase64Value);
        map.put("modulus", retValue);
        return map;
    }

    /**
     * 加密方法 source： 源数据
     */
    public static String encrypt(String data, String publicKey) {
        try {
            /** 得到Cipher对象来实现对源数据的RSA加密 */
            Cipher cipher = Cipher.getInstance(Constants.RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKey));
            /** 执行加密操作 */
            return Base64.urlEncode2Str(cipher.doFinal(data.getBytes(Constants.CHAR_ENCODING)));
        } catch (Exception e) {
            throw new ErrorException(ErrorCode.FAULT, "加密失败");
        }

    }




    /**
     * 解密算法 data:密文
     */
    public static String decrypt(String data, String privateKey) {
        try {
            /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
            Cipher cipher = Cipher.getInstance(Constants.RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKey));
            /** 执行解密操作 */
            return new String(cipher.doFinal(Base64.decodeBase64(data)), Constants.CHAR_ENCODING);
        } catch (Exception e) {
            throw new ErrorException(ErrorCode.FAULT, "解密失败");
        }

    }

    /**
     * 得到公钥
     *
     * @param key 密钥字符串（经过base64编码）
     * @throws Exception
     */
    public static PublicKey getPublicKey(String key) throws Exception {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(key));
        KeyFactory keyFactory = KeyFactory.getInstance(Constants.Algorithm.RSA.algorithm());
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * 得到私钥
     *
     * @param key 密钥字符串（经过base64编码）
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String key) throws Exception {
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(key));
        KeyFactory keyFactory = KeyFactory.getInstance(Constants.Algorithm.RSA.algorithm());
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    /**
     * description 验证签名
     * param
     * return
     */
    public static String sign(String data, String privateKey) {
        try {
            PKCS8EncodedKeySpec pk = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
            KeyFactory fk = KeyFactory.getInstance(Constants.Algorithm.RSA.algorithm());
            PrivateKey priKey = fk.generatePrivate(pk);
            Signature signature = Signature.getInstance(Constants.SIGN_SHA256RSA_ALGORITHM);
            signature.initSign(priKey);
            signature.update(data.getBytes(Constants.CHAR_ENCODING));
            return new String(Base64.encodeBase64(signature.sign()), Constants.CHAR_ENCODING);
        } catch (Exception e) {
            throw new ErrorException(ErrorCode.FAULT, "encrypt fail!");
        }

    }

//    /**
//     * description 验证签名
//     * param
//     * return
//     */
//    public static boolean checkSign(String data, String sign, String publicKey) {
//        try {
//            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
//            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(Base64.decodeBase64(publicKey)));
//            Signature signature = Signature.getInstance(Constants.SIGN_SHA256RSA_ALGORITHM);
//            signature.initVerify(pubKey);
//            signature.update(data.getBytes(Constants.CHAR_ENCODING));
//            return signature.verify(Base64.encodeBase64(sign));
//        } catch (Exception e) {
//            return false;
//        }
//    }

}
